package cn.edu.njpi.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author 朱宗辉
 * @version V1.0
 * @Package cn.edu.njpi.utils
 * @date 2022/4/19 8:40 PM
 */
public class FileUtils {
    public static String readFile(String fileUrl) throws IOException {
        String i = (String) InformUtils.map.get("welcomeText");
        if (i == null) {
            File file = new File(fileUrl);
            StringBuilder welcome = new StringBuilder("这个是操行分管理系统的主入口，你可以在后台管理中修改此文字");
            if (file.exists()) {
                welcome = new StringBuilder();
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
                while (inputStreamReader.ready()) {
                    welcome.append((char) inputStreamReader.read());
                }
                fileInputStream.close();
            } else {
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
                writer.append(welcome.toString());
                writer.close();
                fileOutputStream.close();
            }
            i = welcome.toString();
        }
        return i;
    }

    public static String writeFile(String fileUrl, String text) throws IOException {
        File file = new File(fileUrl);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
        writer.append(text);
        writer.close();
        fileOutputStream.close();
        InformUtils.map.put("welcomeText", text);
        return (String) InformUtils.map.get("welcomeText");
    }
}
